<template>
  <div>
    <el-table :data="roleList" class="margin-top-20" border>
      <!--拓展-->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'verticalCenter']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
            <!--一级权限-->
            <el-col :span="5">
              <el-tag @close="removeRightsTag(item1.id,scope.row)" closable>
                {{item1.authName}}
              </el-tag>
              <icon class="el-icon-caret-right"></icon>
            </el-col>
            <!--二级权限-->
            <el-col :span="19">
              <el-row  v-for="(item2,index2) in item1.children" :key="item2.id" :class="[index2 === 0 ? '' : 'bdtop', 'verticalCenter']">
                <el-col :span="6">
                  <el-tag @close="removeRightsTag(item2.id,scope.row)" closable type="success">{{item2.authName}}</el-tag>
                  <icon class="el-icon-caret-right"></icon>
                </el-col>
                <!--三级权限-->
                <el-col :span="18">
                  <el-tag @close="removeRightsTag(item3.id,scope.row)" closable type="warning" v-for="(item3,index3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>

                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!--编辑-->
          <el-tooltip class="item" effect="dark" content="编辑用户" placement="top" :enterable="false">
            <el-button type="primary" size="small" @click="parent(scope.row)" >
              <i class="el-icon-edit"></i> 编辑
            </el-button>
          </el-tooltip>
          <!--删除-->
          <el-tooltip class="item" effect="dark" content="删除用户" placement="top" :enterable="false">
            <el-button type="danger" size="small"  @click="deleteRole(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </el-tooltip>
          <!--分配权限-->
          <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
            <el-button type="warning" size="small" @click="showAuthorityDistribution(scope.row)">
              <i class="el-icon-setting"></i> 分配权限
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--分配权限对话框-->
    <el-dialog
            title="提示"
            :visible.sync="showAuthorityDialogVisible"
            width="30%">

      <!--树形组件-->
      <el-tree
              :data="rightsList"
              show-checkbox
              node-key="id"
              :props="rightsTree"
              default-expand-all
              :default-checked-keys="this.rightIdList"
              ref="treeRef">
      </el-tree>

      <span slot="footer" class="dialog-footer">
    <el-button @click="showAuthorityDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="authorityDistribution">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    name: "RoleTable",
    data() {
      return {
        roleList: [],
        rightsList: [],
        rightsTree: {
          label: 'authName',
          children: 'children'
        },
        showAuthorityDialogVisible: false,
        rightIdList: ['1','2'],
        roleId: ''
      }
    },
    methods: {
      getRoles() {
        this.$http.get('roles').then(result => {
          this.roleList = result.data.data
        })
      },
      parent(user) {
        this.$emit('showEditorDialog',user)
      },
      deleteRole(user) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(user.id);
          this.$http.delete('roles/' + user.id).then(result => {
            if (result.data.meta.status !== 200) return this.$message.error("删除失败!")
            this.getRoles()
            return this.$message.success("删除成功!")
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 删除权限
      removeRightsTag(rightsid,role) {
        this.$confirm('此操作将永久删除该权限, 是否继续?', '⚠', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete('roles/' + role.id + '/rights/' + rightsid).then(result => {
            if (result.data.meta.status !== 200) return this.$message.error("删除指定权限失败!")
            role.children = result.data.data
            return this.$message.success("删除指定权限成功!")
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      // 获取所有权限 tree
      getRightsTree() {
        this.$http.get('rights/tree').then(result => {
          if (result.data.meta.status !== 200) return this.$message.error('获取权限失败!')
          this.rightsList = result.data.data

        })
      },
      // 展示分配权限
      showAuthorityDistribution(role) {
        // 置空
        this.rightIdList = []
        this.getRightIds(role,this.rightIdList);
        this.getRightsTree()
        this.showAuthorityDialogVisible = true
        this.roleId = role.id
      },
      // 获取 角色已有的权限id
      getRightIds(node,array) {
        // 如果没有children 是三级权限 push id
        if (!node.children) {
          return array.push(node.id)
        }
        node.children.forEach(item => {
          this.getRightIds(item,array)
        })
      },
      // 授权
      authorityDistribution() {
        const ids = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = ids.join(',')

        // 发送请求 , 分配权限
        this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr}).then(result => {
          if (result.data.meta.status !== 200) return this.$message.error("分配权限失败")
          this.getRoles()
          return this.$message.success("分配权限成功")
        })

        // 关闭对话框
        this.showAuthorityDialogVisible = false
      }
    },
    created() {
      this.getRoles()
    }
  }
</script>

<style scoped>

  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .el-tag {
    margin: 7px;
  }
  .verticalCenter {
    display: flex;
    align-items: center;
  }
  .td {
    transition: 0.5s;
  }
</style>